package com.proxy.server.frontend.handler.request.proxy;

import com.proxy.common.constant.ErrorCodeType;
import com.proxy.common.packet.BinaryPacket;
import com.proxy.common.packet.ErrorPacket;
import com.proxy.common.packet.OkPacket;
import com.proxy.parser.result.UseParsedResult;
import com.proxy.router.SQLRouteResult;
import com.proxy.server.context.AppContext;
import com.proxy.server.frontend.FrontendConnection;
import com.proxy.server.frontend.session.Session;

import java.nio.charset.Charset;

/**
 * Created by liufish on 16/7/31.
 */
public class UseDatabaseProxy {


    public static void doProxy(BinaryPacket bin, Session session, SQLRouteResult result) {

        FrontendConnection connection = session.getFrontendConnection();

        UseParsedResult useParsedResult = (UseParsedResult)result.getExtra();
        String  schema = useParsedResult.getDataBase();
        //原来连接有db的情况
        if (connection.getSchema() != null) {

            if (schema.equalsIgnoreCase(connection.getSchema())) {
                connection.write(OkPacket.getOk(++bin.packetId));
                return;
            }

            ErrorPacket error = new ErrorPacket();
            error.packetId = ++bin.packetId;
            error.errNo = ErrorCodeType.ER_DBACCESS_DENIED_ERROR;
            error.message = "Not allowed to change the database!".getBytes(Charset.forName(connection.getCharset()));
            connection.write(error);

            return;
        }

        //原来连接没有db的情况
        if (AppContext.getInstance().getFrontendProxy().getSchema().equalsIgnoreCase(schema)) {
            connection.write(OkPacket.getOk(++bin.packetId));
            return;
        }

        ErrorPacket error = new ErrorPacket();
        error.packetId = ++bin.packetId;
        error.errNo = ErrorCodeType.ER_ACCESS_DENIED_ERROR;
        error.message = ("Access denied for db  " + schema + "!").getBytes(Charset.forName(connection.getCharset()));
        connection.write(error);

    }
}
